// JavaScript Documen
function getinput(name){
  	return $('input[name="'+name+'"]').eq(0);
}
$(function() {
	var allFields=$('input[name^="book"]');
	$('button[name="submit"]').click(function(){
		$('button[name="submit"]').button("option","disabled",true);
		allFields.removeClass('ui-state-error');
		var record = new Array();
		for(var i=0;i<allFields.length;i++){
			var field=allFields.eq(i);
			var book = {
				id: field.attr('name').split('book')[1],
				value: field.val()
			};
			record.push(book);
		}
		$.ajax({
			url: 'booklist.php?action=addrecord&id='+$('#getid').val(),
			dataType:'json',
			data: {
				"record":record
			},
			type: 'POST',
			beforeSend: function(){
				updateTips('請稍後');
			},
			error: function(err){
				console.log(err);
				updateTips('伺服器發生錯誤，請稍後再試');
			},
			success: function(response){
				$('button[name="submit"]').button("option","disabled",false);
				if(response.status=='success'){
					updateTips('下定成功！');
				}else{
					if(response.type=='mysql'){
						updateTips('Mysql發生錯誤，請稍後再試或聯絡管理員');
					}else{
						switch(response.type){
							case 'int':
								t = '必須是數字';
								if(response.min)
									t += '，大於 '+response.min;
								if(response.max)
									t += '，小於 '+response.max;
								break;
							case 'perm':
								t = '權限不足';
								break;
							default:
								t += ' 發生錯誤';
						}
						getinput(response.field).focus();
						updateObjTips(getinput(response.field),t);
					}
				}
			}
	   });
	});
});
